package com.jt.serviceImpl;

import com.jt.service.OrderFileService;
import com.jt.vo.SysResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author dc
 * @Classname OrderFileServiceImpl
 * @Date 2020/5/29 23:41
 */

@Service
public class OrderFileServiceImpl implements OrderFileService {
    /**图片存储根目录*/
    private String fileDirPath="E:/Graduation/jt_Image/";

    /**虚拟网络地址*/
    private String urlPath="http://image.jt.com/";

    @Override
    public SysResult uploadFile(MultipartFile uploadFile) {
        //1.图片校验
        //1.1获取图片名称 a.jpg
        String fileName = uploadFile.getOriginalFilename().toLowerCase();
        //1.2利用正则表达式判断是否为图片
        if(!fileName.matches("^.+\\.(jpg|png|gif|jpge)$")){
            //证明不是图片
            return SysResult.fail();
        }
        //2.防止是恶意程序:根据宽度和高度实现图片校验
        //2.1准备一个图片容器,将字节信息添加进容器中获取宽高
        try {
            BufferedImage bufferImage = ImageIO.read(uploadFile.getInputStream());
            int height = bufferImage.getHeight();
            int width = bufferImage.getWidth();
            if(width==0||height==0){
                //没有宽高一定不是图片
                return SysResult.fail();
            }
            //3.分目录保存,date转化为yyyy/MM/dd/
            String datePath= new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
            //图片本地路径:fileDirPath+datePath+UUID.jpg
            String fileLocalPath=fileDirPath+datePath;
            File dirFile = new File(fileLocalPath);
            if(!dirFile.exists()){
                //创建新目录
                dirFile.mkdirs();
            }
            //4.实现文件上传
            //4.1拼接文件名
            String uuid = UUID.randomUUID().toString().replace("-","");
            String fileType=fileName.substring(fileName.lastIndexOf("."));
            String realFileName=uuid+fileType;
            //4.2上传文件
            String realFilePath = fileLocalPath+realFileName;
            uploadFile.transferTo(new File(realFilePath));
            //图片虚拟地址
            String url=urlPath+datePath+realFileName;
            return SysResult.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            //如果转化出错,则回传错误信息
            return SysResult.fail();
        }
    }
}
